<template>
  <div class="tox-tinymce-aux">
    <textarea
      :id="tinymceId"
      ref="tinymceRef"
      :style="{ visibility: 'hidden' }"
    />
  </div>
</template>

<script setup lang="ts">
import type { Editor, RawEditorSettings } from 'tinymce'
import {
  computed,
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  unref,
  watch
} from 'vue'
import tinymce from 'tinymce/tinymce'
// import './source'
import { tinymceProps } from './props'
// import { THEME_MODE } from './editor'
import { getTinymceBaseConfig } from '@/utils'
import { uploadCommon } from '@/api/common'
import { transferSrcToDataAttribute, transferDataAttributeToSrc } from '@/utils'

console.log('getTinymceBaseConfig', getTinymceBaseConfig())
defineOptions({
  name: 'MRichEditor'
})

const props = defineProps(tinymceProps)
const emits = defineEmits<{
  (event: 'change', val: string): void
  (event: 'update:modelValue', val: string): void
}>()

const tinymceId = new Date().getTime().toString()

const tinymceRef = ref<HTMLElement | null>(null)
const tinymceEditorInstance = ref<Editor | null>(null)

onMounted(() => {
  nextTick(() => {
    initEditorInstance()
  })
})

onBeforeUnmount(() => {
  destory()
})

// // 主题
// const themeMode = computed(() => {
//   return props.theme === THEME_MODE.light ? 'oxide' : 'oxide-dark'
// })

// // 语言
// const lang = computed(() => {
//   return props.lang
// })

// 初始化选项
const initOptions = computed<RawEditorSettings>(() => {
  const { height, toolbar } = props
  return {
    height,
    toolbar,
    selector: `#${tinymceId}`,
    ...getTinymceBaseConfig(),
    setup: (editor) => {
      setupTinymceEditor(editor)
    },
    images_file_types: 'jpeg,jpg,png,gif,bmp,webp',
    images_upload_handler: (blobInfo, success, failure) => {
      // const { type: fileType } = blobInfo.blob()
      // const filename = blobInfo.filename()
      const formData = new FormData()
      formData.append('file', blobInfo.blob())
      // formData.append(filename, filename)

      uploadCommon(formData)
        .then((res) => {
          success(res.data.url)
        })
        .catch(() => {
          failure('上传失败')
        })
      // const reader = new FileReader()
      // reader.onload = function () {
      //   // 调用回调函数，将Base64字符串插入到编辑器中
      //   success(reader.result as unknown as string)
      // }
      // reader.onerror = function () {
      //   failure('上传失败：无法读取文件')
      // }
      // reader.readAsDataURL(blobInfo.blob()) // 将Blob对象转换成Data URL（Base64）
    }
  }
})

// 编辑器启动
function setupTinymceEditor(editor: Editor) {
  tinymceEditorInstance.value = editor

  editor.on('init', () => {
    if (!tinymceEditorInstance.value) return

    props.modelValue && setValue(props.modelValue)
    bindHandlers()
  })

  editor.on(
    props.modelValueEvents.length
      ? props.modelValueEvents.join(' ')
      : 'change keyup undo redo',
    () => {
      const content = getContent()
      emits('update:modelValue', content)
      emits('change', content)
    }
  )
}

// 绑定监听事件
function bindHandlers() {
  watch(
    () => props.modelValue,
    (newVal, oldVal) => {
      if (oldVal !== newVal && newVal !== getContent()) {
        setValue(newVal || '')
      }
    }
  )
}

// 初始化实例
function initEditorInstance() {
  tinymce.init(initOptions.value)

  watch(
    () => props.disabled,
    (newVal) => {
      tinymceEditorInstance.value?.setMode(newVal ? 'readonly' : 'design')
    },
    {
      immediate: true
    }
  )
}

// 销毁
function destory() {
  tinymce?.remove?.(unref(initOptions)?.selector as string)
}

// 设置内容
function setValue(val: string) {
  val = transferDataAttributeToSrc(val)
  tinymceEditorInstance.value && tinymceEditorInstance.value.setContent(val)
}

// 获取内容
function getContent() {
  const content =
    tinymceEditorInstance.value?.getContent({ format: props.outputFormat }) ||
    ''
  return transferSrcToDataAttribute(content)
}
</script>
<style>
.tox-tinymce-aux {
  z-index: 9999 !important;
}
</style>
